package com.djf.eg.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.djf.eg.dao.SysRoleDao;
import com.djf.eg.entity.SysPermission;
import com.djf.eg.entity.SysRole;
import com.djf.eg.util.convert.Entity2Vo;
import com.djf.eg.vo.RoleVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Service
public class RoleService {
	@Autowired
	SysRoleDao sysRoleDao;
	
	public Page<SysRole> getRoles(int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		return sysRoleDao.getRolesByPage();
	}
	
	public List<RoleVo> getRoles() {
		List<SysRole> roleList = sysRoleDao.getAllRoles();
		List<RoleVo> voList = new ArrayList<RoleVo>();
		for (SysRole role : roleList) {
			RoleVo vo = new RoleVo();
			vo = Entity2Vo.roleEntity2Vo(role);
			voList.add(vo);
		}
		return voList;
	}
	
	@Transactional
	public void addRole(SysRole role) {
		sysRoleDao.addRole(role);
		for (SysPermission permission : role.getPermissions()) {
			sysRoleDao.addRolePermission(role.getId(), permission.getId());
		}
	}
	
	@Transactional
	public SysRole updateRole(SysRole role) {
		sysRoleDao.deleteRolePermissions(role.getId());
		for (SysPermission permission : role.getPermissions()) {
			sysRoleDao.addRolePermission(role.getId(), permission.getId());
		}
		sysRoleDao.updateRole(role);
		return role;
	}
	
	@Transactional
	public void deleteRole(int roleId) {
		sysRoleDao.deleteRolePermissions(roleId);
		sysRoleDao.deleteRole(roleId);
	}
}
